Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Find the Difference of Two Arrays

Problem Statement

Given two integer arrays nums1 and nums2, return an answer list of size where:

  • answer[0] is a list of all unique integers in nums1 that are not present in nums2.
  • answer[1] is a list of all unique integers in nums2 that are not present in nums1.

You may return the integers in the list in any order.

Examples

  • Example 1:

    • Input: nums1 = [2, 3, 4], nums2 = [1, 2]
    • Expected Output: [[3, 4], [1]]
    • Justification: The number 2 is common in both arrays. 3 and 4 are unique to nums1, and 1 is unique to nums2.
  • Example 2:

    • Input: nums1 = [0, 2, 4, 6], nums2 = [1, 3, 5, 7]
    • Expected Output: [[0, 2, 4, 6], [1, 3, 5, 7]]
    • Justification: All numbers in both arrays are unique to their respective array as there's no overlap between nums1 and nums2.
  • Example 3:

    • Input: nums1 = [10, 20, 20, 30, 90], nums2 = [20, 30, 40, 50]
    • Expected Output: [[10, 90], [40, 50]]
    • Justification: The numbers 20 and 30 are present in both arrays, so they are excluded. 10 and 90 are unique to nums1, and 40, 50 are unique to nums2. Duplicates in the input are ignored.

Solution

To solve this problem, we'll use a set-based approach because sets efficiently handle uniqueness and membership checks. Initially, we'll convert both input arrays into sets to eliminate any duplicate elements and enable faster lookups. Then, we'll find the difference between these sets in both directions: elements in the first set that are not in the second, and vice versa. This process directly yields the unique elements as per our problem statement.

Using sets is advantageous because set operations like difference and union are highly optimized and concise, making our solution straightforward and efficient. This method also simplifies handling distinct elements, as sets inherently eliminate duplicates.

Step-by-step Algorithm

  1. Initialize Collections: Create two HashSet<Integer> objects: one to store elements from nums2 (named existsInNums2) for quick existence checks, and another (onlyInNums1) to store unique elements found in nums1 but not in nums2.

  2. Fill existsInNums2: Iterate through each element in nums2, adding each element to existsInNums2. This set will be used to check if an element from nums1 exists in nums2.

  3. Identify Unique Elements for nums1:

    • Iterate through each element in nums1.
    • For each element, check if it exists in existsInNums2.
    • If it does not exist, it means the element is unique to nums1. Add this element to onlyInNums1.
  4. Convert to List: Convert onlyInNums1, which is a Set<Integer>, to List<Integer> for the required output format.

  5. Repeat for nums2: Perform steps 1 to 4 for nums2 against nums1 to find elements unique to nums2.

  6. Compile Results: Combine the lists of unique elements from both nums1 and nums2 into a single list of lists and return this as the final result.

Algorithm Walkthrough

Let's consider the Input: nums1 = [10, 20, 20, 30, 90], nums2 = [20, 30, 40, 50]

Initial Setup:

  • We will be executing the getElementsOnlyInFirstList method twice: once with nums1 and nums2 as arguments to find elements unique to nums1, and a second time with their roles reversed to find elements unique to nums2.

First Execution (nums1 against nums2):

  1. Initialize existsInNums2:

    • existsInNums2 is populated with elements from nums2 = [20, 30, 40, 50].
    existsInNums2 = {20, 30, 40, 50}
    
  2. Identify Unique Elements for nums1:

    • Iterate through nums1 = [10, 20, 20, 30, 90].
    • Check each element against existsInNums2.
      • 10 is not in existsInNums2, so add 10 to onlyInNums1.
      • 20 is in existsInNums2, skip.
      • 30 is in existsInNums2, skip.
      • 90 is not in existsInNums2, so add 90 to onlyInNums1.
    onlyInNums1 after first execution = {10, 90}
    
  3. Convert and Compile Results:

    • Convert onlyInNums1 to a list and prepare for return.

Second Execution (nums2 against nums1):

  1. Initialize existsInNums1:

    • existsInNums1 is populated with elements from nums1 = [10, 20, 20, 30, 90].
    existsInNums1 = {10, 20, 30, 90}
    
  2. Identify Unique Elements for nums2:

    • Iterate through nums2 = [20, 30, 40, 50].
    • Check each element against existsInNums1.
      • 20 is in existsInNums1, skip.
      • 30 is in existsInNums1, skip.
      • 40 is not in existsInNums1, so add 40 to onlyInNums2.
      • 50 is not in existsInNums1, so add 50 to onlyInNums2.
    onlyInNums2 after second execution = {40, 50}
    
  3. Convert and Compile Results:

    • Convert onlyInNums2 to a list and prepare for return.

Final Compilation:

  • After both executions, compile the results into a list of lists:
    • For nums1 against nums2, we found [10, 90] as unique to nums1.
    • For nums2 against nums1, we found [40, 50] as unique to nums2.
  • Final Result: [[10, 90], [40, 50]]

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

For each of the two function calls to getElementsOnlyInFirstList in findDifference, the method:

  • Iterates over each element in nums2 to create a set, which is where (n) is the length of nums2.
  • Then, iterates over each element in nums1 to check against the set, which is where (m) is the length of nums1.
  • Since these operations are done for both input arrays (swapping roles), the total time complexity is for each call, resulting in which simplifies to .

Space Complexity

The space complexity is primarily due to the storage of elements in sets and the result list:

  • Two sets are used to store elements from nums1 and nums2, which in the worst case (no overlap) would require space.
  • The output list will have at most space complexity, considering all elements are unique between nums1 and nums2.
  • Hence, the total space complexity is .
Find the Difference of Two Arrays (easy)
Merge Strings Alternately (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Final Compilation:

Code

Complexity Analysis

Time Complexity

Space Complexity